<template>
  <div>
    <div class="home-container" style="padding-top: 10px">
      <el-row :gutter="15" class="home-card-one mb15">
        <el-col :span="6">
          <div class="home-card-item flex" style="height: 100%;max-height: 1140px">
            <div class="menu-box menu-left-box" style="width: 100%">
              <MenuTreeCom
                  ref="menuTreeRef"
                  :treeData="menuTreeData"
                  @treeClick="handleTreeClick"
              />
            </div>
          </div>
        </el-col>

        <el-col :span="18">

          <el-row :gutter="15" class="home-card-one mb15">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div class="home-card-item flex" style="height: auto">
                <div class="flex-margin flex w100" style="display: flex; flex-direction: column;">
                <span>
                  <span class="font15" style="font-weight: bold;">期刊ID：</span><span
                    class="font15">{{ periodicalInfo.id }}</span>
                </span>
                  <span>
                  <span class="font15" style="font-weight: bold;">期刊名：</span><span
                      class="font15">{{ periodicalInfo.name }}</span>
                </span>
                </div>
              </div>
            </el-col>
          </el-row>
          <!-- 年份选择区域 -->
          <el-row class="mb15">
            <el-col :span="24">
              <el-select v-model="selectedYear" multiple @change="handleYearChange" placeholder="选择年份">
                <el-option label="全部" :value="0"></el-option>
                <el-option v-for="year in years" :key="year" :label="year" :value="year"></el-option>
              </el-select>
            </el-col>
          </el-row>

          <el-row :gutter="15" class="home-card-one mb15">
            <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-for="(v, k) in periodicalData" :key="k"
                    :class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }">
              <div class="home-card-item flex">
                <div class="flex-margin flex w100" :class="` home-one-animation${k}`">
                  <div class="flex-auto" style="display: flex; flex-direction: column;">
                    <span class="font25 font-bold">{{ v.name }}:</span>
                    <span class="ml5 font20" style="color : #6690F9;">{{ v.num }}</span>
                  </div>
                  <div class="home-card-item-icon flex" :style="{ background: `var(${v.iconbg})` }">
                    <i class="flex-margin font32" :class="v.icon" :style="{ color: `var(${v.iconcolor})` }"></i>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>

          <el-row class="home-card-one mb15">
            <el-col :span="24">
              <!-- 机构搜索 -->
              <div class="home-card-item">
                <el-input
                    v-model="institutionSearch"
                    placeholder="搜索机构"
                    :prefix-icon="Search"
                    @input="handleInstitutionSearch"
                    clearable
                />
              </div>
            </el-col>
            <!-- 主要发文机构 -->
            <el-col :span="24">
              <div class="home-card-item" style="height: 400px; width: 100%">
                <div style="height: 100%" ref="institutionBarRef"></div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="15" class="home-card-one mb15">
            <!-- 画图部分 -->
            <el-col :span="24">
              <div class="home-card-item" style="height: 300px; width: 100%">
                <div style="height: 100%" ref="JournalBarRef"></div>
              </div>
            </el-col>
          </el-row>

        </el-col>
      </el-row>
    </div>


    <div class="home-container">
      <el-row :gutter="15" class="home-card-one mb15" style="display: flex; align-items: stretch;">
        <!-- 学科占比 -->
        <el-col :span="8">
          <div class="home-card-item" style="height: 100%; width: 100%">
            <div style="height: 100%" ref="subjectPieRef"></div>
          </div>
        </el-col>
        <!--作者占比-->
        <el-col :span="8">
          <el-col :span="24">
            <!-- 作者搜索 -->
            <div>
              <el-input
                  v-model="authorSearch"
                  placeholder="搜索作者"
                  :prefix-icon="Search"
                  @input="handleAuthorSearch"
                  clearable
              />
            </div>
          </el-col>
          <el-col :span="24">
            <div class="home-card-item" style="height: 400px; width: 100%">
              <div style="height: 100%" ref="AuthorRingRef"></div>
            </div>
          </el-col>
        </el-col>
        <!---->
        <el-col :span="8">
          <div class="home-card-item" style="height: 100%; width: 100%">
            <div style="height: 100%" ref="KeywordCloudRef"></div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>

</template>


<script setup lang="ts" name="periodical">

import {reactive, onMounted, ref, watch, nextTick, onActivated} from 'vue';
import * as echarts from 'echarts';
import 'echarts-wordcloud';
import {storeToRefs} from 'pinia';
import {useThemeConfig} from '/@/stores/themeConfig';
import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes';
import MenuTreeCom from "/@/views/system/statics/periodical/components/MenuTreeCom/index.vue";
import {APIResponseData, MenuTreeItemType} from "/@/views/system/console/single/types";
import * as api from './api.ts'
import {Search} from '@element-plus/icons-vue';

type EChartsOption = echarts.EChartsOption;

const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const {themeConfig} = storeToRefs(storesThemeConfig);
const {isTagsViewCurrenFull} = storeToRefs(storesTagsViewRoutes);

let menuTreeData = ref([] as any[]);
let menuTreeCacheData = ref<MenuTreeItemType[]>([]);
let drawerVisible = ref(false);
let drawerFormData = ref<Partial<MenuTreeItemType>>({});
let menuTreeRef = ref<InstanceType<typeof MenuTreeCom> | null>(null);
const periodicalInfo = ref();
periodicalInfo.value = {
  id: '',
  name: ''
}

const getData = async () => {
  // 将分组后的数据转换为树形结构
  // 假设根节点下的 26 个子节点 ID 为 A-Z
  menuTreeData.value = [
    {
      id: 'group',
      name: '智能体',
      children: []
    }
  ];
}
/**
 * 菜单的点击事件
 */
const handleTreeClick = (record: MenuTreeItemType) => {
  periodicalInfo.value = record;
  selectedYear.value = [0];
  initData();
  initInstitutionBarChart();
  initSubjectPieChart();
  initAuthorRingChart();
  initJournalBarChart();
  initKeywordCloudChart();
};

const handleYearChange = () => {
  if (selectedYear.value.includes(0)) {
    selectedYear.value = [0];
    initData();
  } else {
    updateData();
  }
  console.log(selectedYear.value);
  initInstitutionBarChart();
  initSubjectPieChart();
  initAuthorRingChart();
  initJournalBarChart();
  initKeywordCloudChart();
}

const handleDrawerClose = (type?: string) => {
  if (type === 'submit') {
    getData();
  }
  drawerVisible.value = false;
  drawerFormData.value = {};
};

onMounted(() => {
  getData();
});

const docCountRef = ref();
const dataYearsRef = ref();
const impactFactorRef = ref();
const reversoRef = ref();

let years = ref<number[]>([]);
const initData = async () => {
  api.getjournalArticleNum(periodicalInfo.value.id).then((res: any) => {
    let yearss = res.data;
    years.value = Object.keys(yearss).map(year => parseInt(year)).filter(year => yearss[year] > 0);
    console.log(yearss[1901]);
    selectedYear.value = [0];
    let sum = 0;
    let minYear = Math.min(...Object.keys(yearss).map(Number).filter(year => yearss[year] > 0));  // 获取最小年份
    console.log(minYear)
    let maxYear = Math.max(...Object.keys(yearss).map(Number).filter(year => yearss[year] > 0));  // 获取最大年份

    // 计算年份之和
    Object.values(yearss).forEach((num: number) => {
      sum += num;
    });
    docCountRef.value = sum;
    if (minYear == Infinity || maxYear == -Infinity) dataYearsRef.value = "无";
    else dataYearsRef.value = (minYear + "-" + maxYear).toString();
  });
  api.getimpactFactor().then((res: any) => {
    let factor = res.data;
    impactFactorRef.value = factor;
    reversoRef.value = Math.ceil(factor);
  })

}

const updateData = async () => {
  api.getjournalArticleNum(periodicalInfo.value.id).then((res: any) => {
    let yearss = res.data;
    let sum = 0;
    let selectedYearArray = selectedYear.value;

    // 如果 selectedYear 数组为空，直接返回无数据
    if (selectedYearArray.length === 0) {
      dataYearsRef.value = "无";
      docCountRef.value = 0;
      return;
    }

    // 计算 selectedYear 数组中年份的数量之和
    Object.entries(yearss).forEach(([year, count]) => {
      // 如果年份在 selectedYear 数组中
      if (selectedYearArray.includes(Number(year))) {
        sum += count;
      }
    });

    // 更新数量之和
    docCountRef.value = sum;

    // 如果没有符合条件的年份
    if (sum === 0) {
      dataYearsRef.value = "无";
    } else {
      // 设置显示的年份范围
      let minYear = Math.min(...selectedYearArray);
      let maxYear = Math.max(...selectedYearArray);
      dataYearsRef.value = `${minYear}-${maxYear}`;
    }
  });
  api.getimpactFactor().then((res: any) => {
    let factor = res.data;
    impactFactorRef.value = factor;
    reversoRef.value = Math.ceil(factor);
  })
}


//years.value = Array.from({ length: 2024 - 1900  + 1 }, (_, i) => 1900 + i);
const selectedYear = ref()
let periodicalData = ref([
  {
    name: '文献总数',
    num: docCountRef,
    icon: 'iconfont icon-caidan',
    iconbg: '--next-color-primary-lighter',
    iconcolor: '--el-color-primary',
  },
  {
    name: '数据年份',
    num: dataYearsRef,
    icon: 'iconfont icon-ditu',
    iconbg: '--next-color-success-lighter',
    iconcolor: '--el-color-success',
  },
  {
    name: '影响因子',
    num: impactFactorRef,
    icon: 'iconfont icon-zaosheng',
    iconbg: '--next-color-warning-lighter',
    iconcolor: '--el-color-warning',
  },
  {
    name: '引用次数',
    num: reversoRef,
    icon: 'iconfont icon-shidu',
    iconbg: '--next-color-danger-lighter',
    iconcolor: '--el-color-danger',
  }
]);

let global: any = {
  JournalBarChart: null,
  AuthorRingChart: null,
  institutionBarChart: null,
  subjectPieChart: null,
  keywordCloudChart: null,
  typePieChart: null,
  dispose: [null, '', undefined]
};

const JournalBarRef = ref();
const AuthorRingRef = ref();
const institutionBarRef = ref();
const subjectPieRef = ref();
const KeywordCloudRef = ref();

const state = reactive({
  myCharts: [],
  charts: {
    theme: '',
    bgColor: '',
    color: '#303133',
  }
})


//作者发文量
let names = [];
let values = [];

const initAuthorNum = async () => {
  return new Promise((resolve, reject) => {
    api.getAuthorArticleNum(periodicalInfo.value.id, selectedYear.value).then((res: any) => {
      names = [];
      values = [];
      let authorData: SNData = {};
      let data = res.data;
      console.log(data);

      Object.values(data).forEach(yearData => {
        // 遍历该年份的每个作者
        Object.entries(yearData).forEach(([author, count]) => {
          if (author.includes("Anonymous")) {
            return; // 如果作者名包含 "Anonymous"，跳过该作者
          }
          if (!authorData[author]) {
            authorData[author] = 0; // 如果是新作者，初始化发文数量
          }
          authorData[author] += count; // 累加发文数量
        });
      });

      Object.entries(authorData).forEach(([author, totalCount]) => {
        names.push(author);  // 添加作者名
        values.push(totalCount);  // 添加累计的发文数量
      });
      resolve();
    })
        .catch((error) => {
          console.error('API 请求失败:', error);
          reject(error);  // 如果请求失败，调用 reject
        });
  });

}
const initAuthorRingChart = async () => {
  if (periodicalInfo.value.id) await initAuthorNum();
  if (!global.dispose.some((b: any) => b === global.AuthorRingChart)) global.AuthorRingChart.dispose();
  global.AuthorRingChart = <any>echarts.init(AuthorRingRef.value, state.charts.theme);
  let data = [];
  const totalValue = values.reduce((sum, value) => sum + value, 0);
  for (var i = 0; i < names.length; i++) {
    const proportion = Math.floor((values[i] / totalValue) * 100);
    data.push({name: names[i], percent: proportion, value: values[i]});
  }

  const colorList = ['#51A3FC', '#36C78B', '#FEC279', '#968AF5', '#E790E8'];
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '期刊学者发文量',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    tooltip: {
      trigger: 'item', formatter: function (params) {
        // 获取当前的 item 数据
        const data = params.data;
        return `${data.name}<br/>百分比: ${data.percent}%<br/>数量: ${data.value}`;
      },
    },
    graphic: {
      elements: [
        {
          type: 'image',
          z: -1,
          style: {
            image: themeConfig.value.isIsDark,
            width: 230,
            height: 230,
          },
          left: '16.5%',
          top: 'center',
        },
      ],
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: '0%',
      left: '65%',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: names,
      textStyle: {
        rich: {
          name: {
            fontSize: 14,
            fontWeight: 400,
            width: 200,
            height: 35,
            padding: [0, 0, 0, 60],
            color: state.charts.color,
          },
          rate: {
            fontSize: 15,
            fontWeight: 500,
            height: 35,
            width: 40,
            padding: [0, 0, 0, 30],
            color: state.charts.color,
          },
        },
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
        center: ['32%', '50%'],
        itemStyle: {
          color: function (params: any) {
            const h = Math.floor(Math.random() * 360); // 生成随机的色相（0-360）
            const s = Math.floor(Math.random() * 60) + 40; // 生成饱和度（40-100）
            const l = Math.floor(Math.random() * 30) + 40; // 生成亮度（40-70）
            return `hsl(${h}, ${s}%, ${l}%)`;
            //return colorList[params.dataIndex];
          },
        },
        label: {show: false},
        labelLine: {show: false},
        data: data,
      },
    ],
  };
  (<any>global.AuthorRingChart).setOption(option);
  (<any>state.myCharts).push(global.AuthorRingChart);
};

const authorSearch = ref('')


const updateAuthorRingChart = () => {
  let nnames = [];
  let vvalues = [];
  names.forEach((item, index) => {
    // 如果 yAxisData 中的某一项包含搜索框中的值
    if (item.includes(authorSearch.value)) {
      // 添加到新数组
      nnames.push(item);
      vvalues.push(values[index]);
    }
  });
  if (!global.dispose.some((b: any) => b === global.AuthorRingChart)) global.AuthorRingChart.dispose();
  global.AuthorRingChart = <any>echarts.init(AuthorRingRef.value, state.charts.theme);
  let data = [];
  const totalValue = vvalues.reduce((sum, value) => sum + value, 0);
  for (var i = 0; i < names.length; i++) {
    const proportion = Math.floor((vvalues[i] / totalValue) * 100);
    data.push({name: nnames[i], percent: proportion, value: vvalues[i]});
  }

  const colorList = ['#51A3FC', '#36C78B', '#FEC279', '#968AF5', '#E790E8'];
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '期刊学者发文量',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    tooltip: {
      trigger: 'item', formatter: function (params) {
        // 获取当前的 item 数据
        const data = params.data;
        return `${data.name}<br/>百分比: ${data.percent}%<br/>数量: ${data.value}`;
      },
    },
    graphic: {
      elements: [
        {
          type: 'image',
          z: -1,
          style: {
            image: themeConfig.value.isIsDark,
            width: 230,
            height: 230,
          },
          left: '16.5%',
          top: 'center',
        },
      ],
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: '0%',
      left: '65%',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: nnames,
      textStyle: {
        rich: {
          name: {
            fontSize: 14,
            fontWeight: 400,
            width: 200,
            height: 35,
            padding: [0, 0, 0, 60],
            color: state.charts.color,
          },
          rate: {
            fontSize: 15,
            fontWeight: 500,
            height: 35,
            width: 40,
            padding: [0, 0, 0, 30],
            color: state.charts.color,
          },
        },
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
        center: ['32%', '50%'],
        itemStyle: {
          color: function (params: any) {
            const h = Math.floor(Math.random() * 360); // 生成随机的色相（0-360）
            const s = Math.floor(Math.random() * 60) + 40; // 生成饱和度（40-100）
            const l = Math.floor(Math.random() * 30) + 40; // 生成亮度（40-70）
            return `hsl(${h}, ${s}%, ${l}%)`;
            //return colorList[params.dataIndex];
          },
        },
        label: {show: false},
        labelLine: {show: false},
        data: data,
      },
    ],
  };
  (<any>global.AuthorRingChart).setOption(option);
  (<any>state.myCharts).push(global.AuthorRingChart);
}
const handleAuthorSearch = () => {
  if (authorSearch.value) {
    updateAuthorRingChart();
  } else initAuthorRingChart();
}


//期刊逐年发文量
let journalData = [];
let journalNum = [];
const initJournalNum = async () => {
  return new Promise((resolve, reject) => {
    api.getjournalArticleNum(periodicalInfo.value.id)
        .then((res: any) => {
          journalData = [];
          journalNum = [];
          let data = res.data;

          Object.entries(data).forEach(([year, count]) => {
            if (selectedYear.value.includes(Number(year)) || selectedYear.value.includes(0)) {
              if (count > 0) {
                journalData.push(year);  // 添加年份
                journalNum.push(count);   // 添加发文数量
              }
            }
          });
          // 数据填充完毕，调用 resolve
          resolve();
        })
        .catch((error) => {
          console.error('API 请求失败:', error);
          reject(error);  // 如果请求失败，调用 reject
        });
  });
};

const initJournalBarChart = async () => {
  if (periodicalInfo.value.id) {
    await initJournalNum(); // 等待 initJournalNum 完成
  }
  if (!global.dispose.some((b: any) => b === global.JournalBarChart)) global.JournalBarChart.dispose();
  global.JournalBarChart = <any>echarts.init(JournalBarRef.value, state.charts.theme);
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '期刊逐年的发文量折线图',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    grid: {top: 70, right: 20, bottom: 30, left: 30},
    tooltip: {trigger: 'axis'},
    legend: {data: ['期刊发文量'], right: 0},
    xAxis: {
      data: journalData,
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        splitLine: {show: true, lineStyle: {type: 'dashed', color: '#f5f5f5'}},
      },
    ],
    series: [
      {
        name: '期刊发文量',
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: journalNum,
        lineStyle: {color: '#fe9a8b'},
        itemStyle: {color: '#fe9a8b', borderColor: '#fe9a8b'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#fe9a8bb3'},
            {offset: 1, color: '#fe9a8b03'},
          ]),
        },
      },
      // {
      //   name: '最新爬取量',
      //   type: 'line',
      //   symbolSize: 6,
      //   symbol: 'circle',
      //   smooth: true,
      //   data: [0, 24.1, 7.2, 15.5, 42.4, 42.4, 42.4, 24.1, 7.2, 15.5, 42.4, 0],
      //   lineStyle: {color: '#9E87FF'},
      //   itemStyle: {color: '#9E87FF', borderColor: '#9E87FF'},
      //   areaStyle: {
      //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      //       {offset: 0, color: '#9E87FFb3'},
      //       {offset: 1, color: '#9E87FF03'},
      //     ]),
      //   },
      //   emphasis: {
      //     itemStyle: {
      //       color: {
      //         type: 'radial',
      //         x: 0.5,
      //         y: 0.5,
      //         r: 0.5,
      //         colorStops: [
      //           {offset: 0, color: '#9E87FF'},
      //           {offset: 0.4, color: '#9E87FF'},
      //           {offset: 0.5, color: '#fff'},
      //           {offset: 0.7, color: '#fff'},
      //           {offset: 0.8, color: '#fff'},
      //           {offset: 1, color: '#fff'},
      //         ],
      //       },
      //       borderColor: '#9E87FF',
      //       borderWidth: 2,
      //     },
      //   },
      // },
    ],
  };
  (<any>global.JournalBarChart).setOption(option);
  (<any>state.myCharts).push(global.JournalBarChart);
};

//发文机构
let yAxisData = [];
let seriesData = [];
//搜索的特定机构
const institutionSearch = ref('')
const handleInstitutionSearch = () => {
  if (institutionSearch.value) {
    updateInstitutionBarChart();
  } else initInstitutionBarChart();
}

interface SNData {
  [key: string]: number;
}

const initInstitution = async () => {
  return new Promise((resolve, reject) => {
    api.getinstitutionArticleNum(periodicalInfo.value.id, selectedYear.value).then((res: any) => {
      let data = res.data;

      const institutionTotals: SNData = {};
      //遍历每个年份的数据
      Object.values(data).forEach(yearData => {
        // 遍历每个机构的数据
        Object.entries(yearData).forEach(([institution, count]) => {
          if (!institutionTotals[institution]) {
            institutionTotals[institution] = 0; // 初始化该机构的发文数量
          }
          institutionTotals[institution] += count; // 累加发文数量
        });
      });
      const sortedInstitutions = Object.entries(institutionTotals)
          .sort((a, b) => b[1] - a[1]) // 按总发文数量降序排序

      // 3. 准备 yAxis 和 series 的数据
      yAxisData = sortedInstitutions.map(([institution]) => institution);
      seriesData = sortedInstitutions.map(([institution, total]) => total);
      resolve();
    })
        .catch((error) => {
          console.error('API 请求失败:', error);
          reject(error);  // 如果请求失败，调用 reject
        });
  });
}
const initInstitutionBarChart = async () => {
  if (periodicalInfo.value.id) await initInstitution();
  if (!global.dispose.some((b: any) => b === global.institutionBarChart)) global.institutionBarChart.dispose();
  global.institutionBarChart = <any>echarts.init(institutionBarRef.value, state.charts.theme);
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '主要发文机构',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    grid: {
      left: '20%',  // 向右移动图表，留出更多空间给 yAxis 标签
      right: '10%', // 右边留出空间，避免图表与边界太近
      bottom: '10%',
      top: '20%',
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      inverse: true,
      type: 'category',
      data: yAxisData,
    },
    series: [
      {
        name: '发文数量',
        realtimeSort: true,
        data: seriesData,
        type: 'bar'
      }
    ],
    legend: {
      show: true
    }
  };
  (<any>global.institutionBarChart).setOption(option);
  (<any>state.myCharts).push(global.institutionBarChart);
}


const updateInstitutionBarChart = () => {
  let yyAxisData = [];
  let sseriesData = [];
  yAxisData.forEach((item, index) => {
    // 如果 yAxisData 中的某一项包含搜索框中的值
    if (item.includes(institutionSearch.value)) {
      // 添加到新数组
      yyAxisData.push(item);
      sseriesData.push(seriesData[index]);
    }
  });
  if (!global.dispose.some((b: any) => b === global.institutionBarChart)) global.institutionBarChart.dispose();
  global.institutionBarChart = <any>echarts.init(institutionBarRef.value, state.charts.theme);
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '主要发文机构',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    grid: {
      left: '20%',  // 向右移动图表，留出更多空间给 yAxis 标签
      right: '10%', // 右边留出空间，避免图表与边界太近
      bottom: '10%',
      top: '20%',
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      inverse: true,
      type: 'category',
      data: yyAxisData,
    },
    series: [
      {
        name: '发文数量',
        realtimeSort: true,
        data: sseriesData,
        type: 'bar'
      }
    ],
    legend: {
      show: true
    }
  };
  (<any>global.institutionBarChart).setOption(option);
  (<any>state.myCharts).push(global.institutionBarChart);
}
//学科占比
let pieData = [];
const initSubjectNum = async () => {
  return new Promise((resolve, reject) => {
    api.getSubjectNum(periodicalInfo.value.id, selectedYear.value).then((res: any) => {
      let data = res.data;
      // console.log("学科占比");
      // console.log(data);

      const subjectTotals: SNData = {};
      Object.values(data).forEach(yearData => {
        Object.entries(yearData).forEach(([subject, count]) => {
          if (subjectTotals[subject]) {
            subjectTotals[subject] += count;
          } else {
            subjectTotals[subject] = count;
          }
        });
      });

// 将 subjectTotals 转换为数组并排序
      const sortedData = Object.entries(subjectTotals)
          .map(([subject, total]) => ({value: total, name: subject}))
          .sort((a, b) => b.value - a.value) // 按 value 从大到小排序
      pieData = sortedData.slice(0, 8);
      //遍历每个年份的数据
      resolve();
    })
        .catch((error) => {
          console.error('API 请求失败:', error);
          reject(error);  // 如果请求失败，调用 reject
        });
  });

}
const initSubjectPieChart = async () => {
  if (periodicalInfo.value.id) {
    await initSubjectNum();
  }
  if (!global.dispose.some((b: any) => b === global.subjectPieChart)) global.subjectPieChart.dispose();
  global.subjectPieChart = <any>echarts.init(subjectPieRef.value, state.charts.theme);
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '期刊学科占比',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '1%',
      left: 'center'
    },
    series: [
      {
        name: '学科',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 10,
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData,
      }
    ]
  };
  (<any>global.subjectPieChart).setOption(option);
  (<any>state.myCharts).push(global.subjectPieChart);
}

let Clouddata: SNData = [];
const initKeyWord = async () => {
  return new Promise((resolve, reject) => {
    api.getKeywordNum(periodicalInfo.value.id, selectedYear.value).then((res: any) => {
      let data = res.data;
      Clouddata = [];
      Object.values(data).forEach(yearData => {
        // 遍历每个机构的数据
        Object.entries(yearData).forEach(([keyword, count]) => {
          if (!Clouddata[keyword]) {
            Clouddata[keyword] = 0; // 初始化该关键词的数量
          }
          Clouddata[keyword] += count; // 累加关键词数量
        });
      });
      resolve();
    })
        .catch((error) => {
          console.error('API 请求失败:', error);
          reject(error);  // 如果请求失败，调用 reject
        });
  });
}

const initKeywordCloudChart = async () => {
  if (periodicalInfo.value.id) {
    await initKeyWord(); // 根据需要获取数据
  }
  // 如果图表已存在则销毁
  if (!global.dispose.some((b: any) => b === global.keywordCloudChart)) global.keywordCloudChart.dispose();

  // 创建新的词云图
  global.keywordCloudChart = <any>echarts.init(KeywordCloudRef.value, state.charts.theme);

  const keywordCloudData = Object.entries(Clouddata).map(([keyword, count]) => ({
    name: keyword,
    value: count
  }));
  //console.log(keywordCloudData);

  // 词云图的配置
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '期刊发文主题词云',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}', // 词语和数量
    },
    series: [
      {
        type: 'wordCloud',
        //maskImage: maskIamge,
        shape: 'diamond', // 形状可以根据需要调整，如 circle, diamond, etc.
        sizeRange: [12, 50], // 设置词云中词语大小的范围
        rotationRange: [-30, 30], // 旋转角度范围
        rotationStep: 45, // 每个词语的旋转角度步长
        gridSize: 8, // 网格大小
        drawOutOfBound: false, // 是否允许词语超出边界
        textStyle: {
          color: function () {
            const r = Math.floor(Math.random() * 256); // Red
            const g = Math.floor(Math.random() * 256); // Green
            const b = Math.floor(Math.random() * 256); // Blue
            return `rgb(${r}, ${g}, ${b})`;
          },
        },
        data: keywordCloudData,
      },
    ],
  };

  // 设置词云图
  (<any>global.keywordCloudChart).setOption(option);
  (<any>state.myCharts).push(global.keywordCloudChart);
};


// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    for (let i = 0; i < state.myCharts.length; i++) {
      setTimeout(() => {
        (<any>state.myCharts[i]).resize();
      }, i * 100);
    }
  });
};
// 批量设置 echarts resize
const initEchartsResize = () => {
  window.addEventListener('resize', initEchartsResizeFun);
};
// 页面加载时
onMounted(() => {
  initEchartsResize();
});
// 由于页面缓存原因，keep-alive
onActivated(() => {
  initEchartsResizeFun();
});
// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
    () => isTagsViewCurrenFull.value,
    () => {
      initEchartsResizeFun();
    }
);
// 监听 vuex 中是否开启深色主题
watch(
    () => themeConfig.value.isIsDark,
    (isIsDark) => {
      nextTick(() => {
        state.charts.theme = isIsDark ? 'dark' : '';
        state.charts.bgColor = isIsDark ? 'transparent' : '';
        state.charts.color = isIsDark ? '#dadada' : '#303133';
        setTimeout(() => {
          initJournalBarChart();
        }, 500);
        setTimeout(() => {
          initAuthorRingChart();
        }, 700);
        setTimeout(() => {
          initInstitutionBarChart();
        }, 1000);
        setTimeout(() => {
          initSubjectPieChart();
        }, 1200);
        setTimeout(() => {
          initKeywordCloudChart();
        });
      });
    },
    {
      deep: true,
      immediate: true,
    }
);

</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
  overflow: hidden;

  .home-card-one,
  .home-card-two,
  .home-card-three {
    .home-card-item {
      width: 100%;
      height: 130px;
      border-radius: 4px;
      transition: all ease 0.3s;
      padding: 20px;
      overflow: hidden;
      background: var(--el-color-white);
      color: var(--el-text-color-primary);
      border: 1px solid var(--next-border-color-light);

      &:hover {
        box-shadow: 0 2px 12px var(--next-color-dark-hover);
        transition: all ease 0.3s;
      }

      &-icon {
        width: 70px;
        height: 70px;
        border-radius: 100%;
        flex-shrink: 1;

        i {
          color: var(--el-text-color-placeholder);
        }
      }

      &-title {
        font-size: 15px;
        font-weight: bold;
        height: 30px;
      }
    }
  }

  .home-card-one {
    @for $i from 0 through 3 {
      .home-one-animation#{$i} {
        opacity: 0;
        animation-name: error-num;
        animation-duration: 0.5s;
        animation-fill-mode: forwards;
        animation-delay: calc($i/10) + s;
      }
    }
  }

  .home-card-two,
  .home-card-three {
    .home-card-item {
      height: 400px;
      width: 100%;
      overflow: hidden;

      .home-monitor {
        height: 100%;

        .flex-warp-item {
          width: 25%;
          height: 111px;
          display: flex;

          .flex-warp-item-box {
            margin: auto;
            text-align: center;
            color: var(--el-text-color-primary);
            display: flex;
            border-radius: 5px;
            background: var(--next-bg-color);
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transition: all 0.3s ease;
            }
          }

          @for $i from 0 through $homeNavLengh {
            .home-animation#{$i} {
              opacity: 0;
              animation-name: error-num;
              animation-duration: 0.5s;
              animation-fill-mode: forwards;
              animation-delay: calc($i/10) + s;
            }
          }
        }
      }
    }
  }
}
</style>